package com.yhm.testSpringMvc.readWriteLock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockCache {
    public static void main(String[] args) {
    }

    private Map<String, Object> cache = new HashMap<>();
    private Object returnObj = null;
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public synchronized Object getCacheBySynchronized(String key) {
        Object obj = null;
        if (returnObj == null) {
            returnObj = "查数据库";
        }
        return obj;
    }

    public Object getCacheByReadWriteLock(String key) {

        readWriteLock.readLock().lock();
        try {
            returnObj = cache.get(key);
            if (returnObj == null) {
                readWriteLock.readLock().unlock();
                try {
                    readWriteLock.writeLock().lock();

                    if (returnObj == null) {
                        returnObj = "查数据库";//做真正LOAD到缓存的事情
                    }
                } catch (Exception e) {
                } finally {

                    readWriteLock.writeLock().unlock();
                }
                readWriteLock.readLock().lock();
            }
        } catch (Exception e) {

        } finally {
            readWriteLock.readLock().unlock();
        }
        return returnObj;
    }
}
